import axios from "axios";
import { getLocationParam } from "./tools";

const instance = axios.create({
  baseURL: process.env.VUE_APP_API_URI,
  timeout: 5000,
});

/**
 * 请求拦截
 */
instance.interceptors.request.use(
  (config) => {
    // eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2Jhc2VfaWQiOiIxMDA0fDE2NTgzMDU3MzQwMDQifQ.jStckcJiAskRfCLjbX8nXe3kc6ZbzT5Ngz7fuVldPew
    // eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2Jhc2VfaWQiOiIyNTk0MHwxNjU4MzA1MDY2Nzg3In0.-mVhYrkSc9yDFClqKRafZUfiyalix1sPWB_90HzYMoc
    // config.headers["Authorization"] =
    //   "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2Jhc2VfaWQiOiIyMjAxMXwxNjU4NzEyMjAxNzg5In0.CpZ0ZW2fiCsIECWsuMPmv3QythiFa944l-Y4029f6nw"; //测试
    if (getLocationParam("token")) {
      config.headers["Authorization"] = getLocationParam("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
instance.interceptors.response.use(
  (response) => {
    if (response.data) {
      const { code, data = null } = response.data;
      if (code === 200) {
        return data;
      }
      return Promise.reject(response.data);
    } else {
      // 文件上传没有返回值
      return null;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const post = (url, params = {}, opt = {}) => {
  return instance({ url, method: "POST", data: params, ...opt });
};

export const get = (url, params = {}, opt = {}) => {
  return instance({ url, method: "GET", params, ...opt });
};

export const put = (url, params = {}, opt = {}) => {
  return instance({ url, method: "PUT", data: params, ...opt });
};

export const del = (url, params = {}, opt = {}) => {
  return instance({ url, method: "DELETE", data: params, ...opt });
};
export const upload = (url, file, opt = {}) => {
  return instance({
    url,
    method: "PUT",
    data: file,
    headers: { "Content-Type": file.type },
    ...opt,
  });
};
